package mysql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import objects.Movie;
import objects.Series;

public class SeriesQueries {
	
	private static final String DATABASE_URL = "jdbc:mysql://localhost/MovieBase";
	private static final String USERNAME = "moviebase";
	private static final String PASSWORD = "moviebase";

	private Connection connection = null;
	private PreparedStatement selectAllSeries = null;
	private PreparedStatement insertNewSeries = null;
	private PreparedStatement checkoutSeries = null;
	
	public SeriesQueries() {
		try {
			connection = DriverManager.getConnection(DATABASE_URL, USERNAME,
					PASSWORD);

			selectAllSeries = connection
					.prepareStatement("SELECT * FROM Series");

			insertNewSeries = connection
					.prepareStatement("INSERT INTO Series (seid, title, season, episode, location) VALUES "
							+ "(?,?,?,?,?)");
			checkoutSeries = connection
					.prepareStatement("UPDATE `MovieBase`.`Series` SET `out`=? WHERE `seid`=?");
			
		} catch (SQLException e) {
			System.out.println(e);
		}
	}

	public List<Series> getAllSeries() {
		List<Series> results = null;
		ResultSet resultSet = null;

		try {
			resultSet = selectAllSeries.executeQuery();
			results = new ArrayList<Series>();

			while (resultSet.next()) {
				results.add(new Series(resultSet.getInt("seid"), resultSet.getString("title"),
						resultSet.getInt("season"), resultSet.getString("episode"), resultSet
								.getInt("location"), resultSet.getInt("out")));
			}
		} catch (SQLException e) {
			System.out.println(e);
		} finally {
			try {
				resultSet.close();
			} catch (SQLException e) {

			}
		}
		return results;
	}
	
	public int addSeries(int seid, String title, int season, String episode, int loc, int out) {
		int result = 0;
		
		try {
			insertNewSeries.setInt(1, seid);
			insertNewSeries.setString(2, title);
			insertNewSeries.setInt(3, season);
			insertNewSeries.setString(3, episode);
			insertNewSeries.setInt(4, loc);
			
			result = insertNewSeries.executeUpdate();
		}
		catch (SQLException e) {
			System.out.println(e);
			close();
		}
		
		return result;
	}
	
	public void close() {
		try {
			connection.close();
		}
		catch (SQLException e) {
			System.out.println(e);
		}
	}

	public int checkoutSeries(int moid, int out) {
		int result = 0;

		try {
			checkoutSeries.setInt(1, out);
			checkoutSeries.setInt(2, moid);

			result = checkoutSeries.executeUpdate();
		} catch (SQLException e) {
			System.out.println(e);
			close();
		}

		return result;
	}


}
